package com.itheima.app.manager;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.itheima.app.interceptor.UserHolder;
import com.itheima.autoconfig.oss.OssTemplate;
import com.itheima.domain.db.UserInfo;
import com.itheima.domain.mongo.Comment;
import com.itheima.domain.mongo.FriendMovement;
import com.itheima.domain.mongo.Movement;
import com.itheima.domain.vo.CommentVo;
import com.itheima.domain.vo.MovementVo;
import com.itheima.domain.vo.PageBeanVo;
import com.itheima.service.mongo.CommentService;
import com.itheima.service.mongo.MovementService;
import com.itheima.util.ConstantUtil;
import com.itheimma.service.db.UserInfoService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.ArrayOperators;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Component
public class MovementManager {

    @DubboReference
    private CommentService commentService;

    @DubboReference
    private MovementService movementService;

    @DubboReference
    private UserInfoService userInfoService;

    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    //发布动态
    public void saveMovement(Movement movement , MultipartFile[] imageContent) throws IOException {
        /*
        * service中可以使用movement来保存好友表，个人表，详情表
        * */
        Long id = UserHolder.get().getId();

        /*用于获取图片url的集合*/
        ArrayList<String> urls = new ArrayList<>();
        if (ArrayUtil.isNotEmpty(imageContent)) {
            for (MultipartFile multipartFile : imageContent) {
                String url = ossTemplate.upload(multipartFile.getOriginalFilename(), multipartFile.getInputStream());
                urls.add(url);
            }
        }

        movement.setId(ObjectId.get());
        movement.setMedias(urls);
        movement.setUserId(id);
        movement.setCreated(System.currentTimeMillis());
        movement.setState(0); //给华为审核
        movement.setSeeType(1);

        //发布动态到mq中，主体是tanhua-movement-check，存了一个动态id
        rocketMQTemplate.convertAndSend("tanhua-movement-check" ,movement.getId().toHexString());

        movementService.saveMovement(movement);
    }

    //查询我的动态
    public ResponseEntity findMyMovement(Long id , Integer pageNum , Integer pageSize){
        /*
        * 查询含有动态详情的pageBeanVo
        * 查出Mysql中的userInfo
        * 取出pageBeanVo中的动态详情
        * 封装进MovementVo，填进pageBeanVo返回pageBeanVo
        * */
        //Long id = UserHolder.get().getId();
        PageBeanVo pageBeanVo = movementService.findMyMovement(id, pageNum, pageSize);
        UserInfo userInfo = userInfoService.findById(id);

        //此处返回值需要强转
        List<Movement> movementList = (List<Movement>) pageBeanVo.getItems();
        ArrayList<MovementVo> movementVos = new ArrayList<>();

        if (CollectionUtil.isNotEmpty(movementList)){
            for (Movement movement : movementList) {
                MovementVo movementVo = new MovementVo();
                movementVo.setUserInfo(userInfo);
                movementVo.setMovement(movement);
                if (stringRedisTemplate.hasKey(StrUtil.format(ConstantUtil.MOVEMENT_LOVE, movement.getId(),id))){
                    movementVo.setHasLoved(1);
                }
                if (stringRedisTemplate.hasKey(StrUtil.format(ConstantUtil.MOVEMENT_LIKE, movement.getId(),id))){
                    movementVo.setHasLiked(1);
                }
                movementVos.add(movementVo);
            }
        }

        pageBeanVo.setItems(movementVos);
        return ResponseEntity.ok(pageBeanVo);
    }

    //查看好友动态
    public ResponseEntity findFriendMovement(Integer pageNum, Integer pageSize) {
        Long id = UserHolder.get().getId();
        PageBeanVo pageBeanVo = movementService.findFriendMovement(id, pageNum, pageSize);

        List<Movement> friendMovementList =(List<Movement>) pageBeanVo.getItems();
        ArrayList<MovementVo> movementVos = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(friendMovementList)){
            for (Movement movement : friendMovementList) {
                MovementVo movementVo = new MovementVo();
                //动态详情中包含着该动态的用户id，也就是用户朋友的id信息
                UserInfo userInfo = userInfoService.findById(movement.getUserId());
                movementVo.setUserInfo(userInfo);
                movementVo.setMovement(movement);
                if (stringRedisTemplate.hasKey(StrUtil.format(ConstantUtil.MOVEMENT_LOVE,movement.getId(),id))){
                    movementVo.setHasLoved(1);
                }
                if (stringRedisTemplate.hasKey(StrUtil.format(ConstantUtil.MOVEMENT_LIKE , movement.getId() , id))){
                    movementVo.setHasLiked(1);
                }
                movementVos.add(movementVo);
            }
        }

        pageBeanVo.setItems(movementVos);

        return ResponseEntity.ok(pageBeanVo);
    }

    //查询推荐动态
    public ResponseEntity findRecommendMovement(Integer pageNum , Integer pageSize){
        Long id = UserHolder.get().getId();
        PageBeanVo pageBeanVo = movementService.findRecommendMovement(id, pageNum, pageSize);
        List<Movement> movementList =(List<Movement>) pageBeanVo.getItems();

        ArrayList<MovementVo> movementVos = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(movementList)){
            for (Movement movement : movementList) {
                UserInfo userInfo = userInfoService.findById(movement.getUserId());
                MovementVo movementVo = new MovementVo();
                movementVo.setUserInfo(userInfo);
                movementVo.setMovement(movement);
                if (stringRedisTemplate.hasKey(StrUtil.format(ConstantUtil.MOVEMENT_LOVE, movement.getId(),id))){
                    movementVo.setHasLoved(1);
                }
                if (stringRedisTemplate.hasKey(StrUtil.format(ConstantUtil.MOVEMENT_LIKE, movement.getId(),id))){
                    movementVo.setHasLiked(1);
                }
                movementVos.add(movementVo);
            }
        }

        pageBeanVo.setItems(movementVos);
        return ResponseEntity.ok(pageBeanVo);
    }

    //动态点赞
    public ResponseEntity setMovementLike(String publishId){
        /*封装comment数据，传入*/
        Long id = UserHolder.get().getId();
        Comment comment = new Comment();
        comment.setCreated(System.currentTimeMillis());
        comment.setCommentType(1);
        comment.setPublishId(new ObjectId(publishId));
        comment.setUserId(id);
        Movement movement = movementService.findById(publishId);
        comment.setPublishUserId(movement.getUserId());
        //获取点赞数量
        Integer likeCount = commentService.saveComment(comment);

        /*1 是 高亮 ， 0 是取消*/
        stringRedisTemplate.opsForValue().set(StrUtil.format(ConstantUtil.MOVEMENT_LIKE, new ObjectId(publishId),id), "1");
        return ResponseEntity.ok(likeCount);
    }

    //取消点赞
    public ResponseEntity removeMovementLike(String publishId){
        Long id = UserHolder.get().getId();
        Integer likeCount = commentService.removeComment(1, publishId, id);
        stringRedisTemplate.delete(StrUtil.format(ConstantUtil.MOVEMENT_LIKE, new ObjectId(publishId),id));
        return ResponseEntity.ok(likeCount);
    }

    //喜欢+1
    public ResponseEntity setMovementLove(String publishId){
        Long id = UserHolder.get().getId();
        Comment comment = new Comment();
        comment.setCreated(System.currentTimeMillis());
        comment.setUserId(id);
        comment.setPublishId(new ObjectId(publishId));
        comment.setCommentType(3);
        Movement movement = movementService.findById(publishId);
        comment.setPublishUserId(movement.getUserId());

        Integer LoveCount = commentService.saveComment(comment);

        stringRedisTemplate.opsForValue().set(StrUtil.format(ConstantUtil.MOVEMENT_LOVE, new ObjectId(publishId),id),"1");
        return ResponseEntity.ok(LoveCount);
    }

    //喜欢-1
    public ResponseEntity removeMovementLove(String publishId){
        Long id = UserHolder.get().getId();
        Integer LoveCount = commentService.removeComment(3, publishId, id);
        stringRedisTemplate.delete(StrUtil.format(ConstantUtil.MOVEMENT_LOVE, new ObjectId(publishId),id));
        return ResponseEntity.ok(LoveCount);
    }

    //查询单条动态
    public ResponseEntity findSingleMovement(String publishId){
        Long id = UserHolder.get().getId();
        Movement movement = movementService.findById(publishId);
        UserInfo userInfo = userInfoService.findById(movement.getUserId());
        MovementVo movementVo = new MovementVo();
        movementVo.setUserInfo(userInfo);
        movementVo.setMovement(movement);
        if (stringRedisTemplate.hasKey(StrUtil.format(ConstantUtil.MOVEMENT_LOVE, movement.getId(),id))){
            movementVo.setHasLoved(1);
        }
        if (stringRedisTemplate.hasKey(StrUtil.format(ConstantUtil.MOVEMENT_LIKE, movement.getId(),id))){
            movementVo.setHasLiked(1);
        }
        return ResponseEntity.ok(movementVo);
    }

    //查询动态列表
    public ResponseEntity findMovementList(Integer pageNum ,Integer pageSize,String publishId){

        PageBeanVo pageBeanVo = commentService.findCommentByPage(publishId, pageNum, pageSize);

        List<Comment> commentList =(List<Comment>) pageBeanVo.getItems();

        ArrayList<CommentVo> commentVos = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(commentList)){
            for (Comment comment : commentList) {
                Long userId = comment.getUserId();
                UserInfo userInfo = userInfoService.findById(userId);
                CommentVo commentVo = new CommentVo();
                commentVo.setId(comment.getId().toHexString());
                commentVo.setAvatar(userInfo.getAvatar());
                commentVo.setNickname(userInfo.getNickname());
                commentVo.setContent(comment.getContent());
                commentVo.setCreateDate(DateUtil.formatDate(new Date(comment.getCreated())) );
                commentVos.add(commentVo);
            }
        }

        //设置 分页
        pageBeanVo.setItems(commentVos);
        return ResponseEntity.ok(pageBeanVo);
    }

    //发表评论
    public void saveMovementComment(String content ,String publishId){
        Long id = UserHolder.get().getId();

        //封装comment
        Comment comment = new Comment();
        comment.setCreated(System.currentTimeMillis());
        comment.setPublishId(new ObjectId(publishId));
        comment.setCommentType(2);
        comment.setUserId(id);
        Movement movement = movementService.findById(publishId);
        comment.setPublishUserId(movement.getUserId());
        comment.setContent(content);

        commentService.saveComment(comment);
    }
}
